package com.wmada.toolkit.common.secure;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author will.ma
 * @date 2017/3/11
 */
public class Digest {

    private static final Logger LOGGER = LoggerFactory.getLogger(Digest.class);

    private MessageDigest md = null;

    public Digest(MessageDigest md) {
        this.md = md;
    }

    public Digest(String algorithm) {
        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            LOGGER.error("初始化 Digest of [" + algorithm + "] 失败！", e);
        }
    }

    public String getDigest(String message) {
        if (md != null && message != null) {
            return EncodeUtils.bytes2Hex(md.digest(message.getBytes(StandardCharsets.UTF_8)));
        } else {
            return null;
        }
    }

    public byte[] getDigest(byte[] data) {
        if (md != null && data != null) {
            return md.digest(data);
        } else {
            return null;
        }
    }

}
